#!/usr/bin/python3.0


import csv
import re

# google csv are in UTF-16. So our processed file will have the same encoding.
import sys
import codecs
#sys.stdout.encoding = codecs.getwriter('utf16')(sys.stdout)

def uniq(alist):
	'''Remove duplicate entries from a list preserving the order of the entries.
	Taken from http://code.activestate.com/recipes/52560/

	Keyword arguments:
	alist -- any list 

	Returns: list
	'''

	set = {}
	return [set.setdefault(e,e) for e in alist if e not in set]


def parsa(contacts,outputfile):
	'''Processes a CSV google contacts file searching for entries
	with duplicate phone numbers.
	
	Keyword arguments: 
	contacts -- the list of contacts in CSV format as exported by google.

	Returns: none
	'''

	phonesregex = re.compile("(.*Mobile,)(.*?)(,.*)")

	for contact in contacts:
		userwithmobile = phonesregex.match(contact)
		if userwithmobile:
				# we put the numbers in a list (the numbers delimiter inside of the 
				# cvs field is ::: ) then we remove duplicates
				numbers = userwithmobile.group(2).split(" ::: ") 
				uniqednumbers = (uniq(numbers))

				# convert the list back to a properly formatted string
				firstnum = True
				newstring = ""
				for num in uniqednumbers:
					if firstnum:
						firstnum = False
						newstring += num
					else:
						newstring += " ::: " + num

				o.write (userwithmobile.group(1) + newstring + userwithmobile.group(3) + "\n")
		else:
				o.write (contact)
			

if __name__  == '__main__':
	contacts = []
	i = open("google.csv", "r", encoding="utf16")
	o = open("parsed.csv", "w", encoding="utf16")
	parsa (i,o)
